<?php

namespace common\models\tsline;

use Yii;
use common\helpers\Utils;
use yii\helpers\HtmlPurifier;
use common\helpers\FormatConverter;
use common\helpers\Url;
use common\models\user\UserLike;

/**
 * This is the model class for table "{{%ts_article}}".
 *
 * @property int $id
 * @property int $channel_id 频道ID
 * @property int $format 文章类型：news,video,gallery
 * @property string $title 标题
 * @property string $subtitle 副标题
 * @property string $keywords 关键词：多关键词以空格、逗号等分割
 * @property string $description 简介
 * @property string $author 作者
 * @property string $copyfrom 来源
 * @property int $bloger_id 泰山号ID
 * @property int $user_id 用户ID
 * @property int $admin_id 是否管理员
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class TslineArticle extends \yii\db\ActiveRecord implements \common\base\ShareDataInterface {

    private $_content;

    use \common\traits\Constants;
    use \common\traits\TimestampBehavior;

    /**
     * @var STATUS_DEFAULT 0 未启用
     * @var STATUS_ENABLE 1 启用
     */
    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 1;
    const STATUS_DELETED = -1;

    /**
     * @var FORMAT_VIDEO video
     * @var FORMAT_NEWS news
     * @var FORMAT_GALLERY gallery
     */
    const FORMAT_TEXT = 0;
    const FORMAT_THUMB = 1;
    const FORMAT_BANNER = 2;
    const FORMAT_GRALLEY = 3;

    /**
     * @var FORMAT_VIDEO video
     * @var FORMAT_NEWS news
     * @var FORMAT_GALLERY gallery
     */
    const TYPE_TEXT = 0;
    const TYPE_NEWS = 1;
    const TYPE_VIDEO = 2;
    const TYPE_GALLERY = 3;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%ts_article}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['channel_id', 'format', 'style', 'bloger_id', 'user_id', 'admin_id', 'status', 'pubdate', 'recommend_time', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['title'], 'required'],
            [['title', 'subtitle', 'copyfrom'], 'string', 'max' => 128],
            [['keywords', 'description'], 'string', 'max' => 255],
            [['author'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'channel_id' => '频道ID',
            'format' => '文章类型',
            'style' => '版式设置',
            'title' => '标题',
            'subtitle' => '副标题',
            'keywords' => '关键词：多关键词以空格分割',
            'description' => '简介',
            'author' => '作者',
            'copyfrom' => '来源',
            'bloger_id' => '泰山号ID',
            'user_id' => '用户ID',
            'admin_id' => '是否管理员',
            'status' => '状态',
            'pubdate' => '发布时间',
            'recommend_time' => '推荐时间',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    public function getData() {
        return $this->hasOne(TslineArticleData::className(), ['article_id' => 'id']);
    }

    public function getBloger() {
        return $this->hasOne(TslineBloger::className(), ['id' => 'bloger_id']);
    }

    public function getStats() {
        return $this->hasOne(TslineArticleStatistic::className(), ['article_id' => 'id']);
    }

    public function getGallery() {
        return $this->hasMany(TslineArticleGallery::className(), ['article_id' => 'id']);
    }

    public function getChannel() {
        return $this->hasOne(TslineChannel::className(), ['id' => 'channel_id']);
    }

    public function getVideo() {
        return $this->hasOne(TslineArticleVideo::className(), ['article_id' => 'id']);
    }

    public function setContent() {
        if (!$this->data) {
            return '';
        }
        $content = $this->data->body;
        if ($content) {
            $content = FormatConverter::appendRemoteDomain($content);
        }
        $this->_content = HtmlPurifier::process($content);
    }

    public function getContent() {
        return $this->_content;
    }

    public function getCancel() {
        return $this->hasOne(TsChannel::className(), ['id' => 'channel_id']);
    }

    public function getThumbs() {
        return $this->getGallery()->andWhere(['!=', 'is_thumb', 0])->orderBy(['is_thumb' => SORT_ASC]);
    }

    public function getLikes() {
        return $this->hasMany(UserLike::className(), ['model_id' => 'id'])->andWhere([
            'model' => UserLike::MODEL_ARTICLE
        ])->count();
    }

    public function getLiked() {
        return $this->hasOne(UserLike::className(), ['model_id' => 'id'])->andWhere([
            'model' => UserLike::MODEL_ARTICLE,
            'user_id' => Yii::$app->user->id
        ])->exists();
    }

    public function getStatsText() {
        return '1321 播放 0赞 3评论';
    }

    public function fields() {
        $fields = parent::fields();
        unset($fields['admin_id'], $fields['status']);
        $fields['mark'] = 'statsText';
        $fields['thumb'] = function($model) {
            if ($model->thumb) {
                return "https://img.lnts.cn" . $model->thumb;
            }
            return '';
        };
        $fields[] = 'video';
        return $fields;
    }

    public function getShareImage() {
        if ($this->thumb) {
            return Url::attach($this->thumb);
        }
        $image = '';
        $gallery = $this->thumbs;
        if (!empty($gallery)) {
            $firstImage = array_shift($gallery);
            $image = Url::attach($firstImage->image);
        }
        return $image;
    }

    public static function findShareById($id) {
        $model = static::findOne($id);
        if (!$model) {
            return null;
        }
        return [
            'title' => $model->title,
            'desc' => \common\helpers\StringHelper::truncate($model->content, 128),
            'img_url' => $model->shareImage,
            'link' => Url::share(['/tsline/article/view', ['id' => $model->id]]),
        ];
    }

}
